<template>
  <div v-if="hasAdminAccess">
    <h2 class="page-title">
      <el-icon><User /></el-icon>
      用户管理
    </h2>
    <div class="card">
      <div class="table-operations">
        <el-button type="primary" :icon="Plus" @click="handleAddUser">
          添加用户
        </el-button>
        <div style="display: flex; gap: 10px">
          <el-button :icon="Refresh" @click="handleRefresh" :loading="loading">
            刷新
          </el-button>
          <el-input
            placeholder="搜索用户（用户名/姓名/手机号）"
            style="width: 350px"
            v-model="userSearch"
            clearable
            @keyup.enter="handleSearch"
            @input="handleSearchInput"
          >
            <template #append>
              <el-button :icon="Search" @click="handleSearch"></el-button>
            </template>
          </el-input>
        </div>
      </div>

      <el-table :data="userList" stripe style="width: 100%" v-loading="loading">
        <el-table-column
          prop="id"
          label="ID"
          width="80"
          align="center"
        ></el-table-column>
        <el-table-column
          prop="userName"
          label="用户名"
          width="120"
        ></el-table-column>
        <el-table-column
          prop="realName"
          label="姓名"
          width="120"
        ></el-table-column>
        <el-table-column
          prop="userRole"
          label="角色"
          width="120"
          align="center"
        >
          <template #default="scope">
            <el-tag
              v-if="scope.row.userRole === 'superAdmin'"
              type="danger"
              effect="dark"
            >
              <el-icon><User /></el-icon>
              超级管理员
            </el-tag>
            <el-tag
              v-else-if="scope.row.userRole === 'admin'"
              type="warning"
              effect="dark"
            >
              <el-icon><User /></el-icon>
              管理员
            </el-tag>
            <el-tag
              v-else-if="scope.row.userRole === 'boss'"
              type="info"
              effect="dark"
            >
              <el-icon><User /></el-icon>
              老板
            </el-tag>
            <el-tag v-else type="success" effect="dark">
              <el-icon><User /></el-icon>
              员工
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column
          prop="phone"
          label="手机号"
          width="130"
        ></el-table-column>
        <el-table-column
          prop="userProfile"
          label="个人简介"
          min-width="150"
          show-overflow-tooltip
        ></el-table-column>
        <el-table-column
          prop="createdTime"
          label="注册时间"
          width="180"
        ></el-table-column>
        <el-table-column label="操作" width="200" fixed="right" align="center">
          <template #default="scope">
            <el-button
              size="small"
              type="primary"
              :icon="Edit"
              @click="handleEdit(scope.row)"
              :disabled="
                scope.row.userRole === 'superAdmin' &&
                currentUserRole !== 'superAdmin'
              "
            >
              编辑
            </el-button>
            <el-button
              size="small"
              type="danger"
              :icon="Delete"
              @click="handleDelete(scope.row)"
              :disabled="
                scope.row.userRole === 'superAdmin' &&
                currentUserRole !== 'superAdmin'
              "
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[5, 10, 20, 50]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        ></el-pagination>
      </div>
    </div>

    <!-- 添加/编辑用户对话框 -->
    <el-dialog
      :title="dialogTitle"
      v-model="dialogVisible"
      width="700px"
      :close-on-click-modal="false"
    >
      <el-form :model="form" :rules="rules" ref="formRef" label-width="100px">
        <el-form-item label="用户名" prop="userName">
          <el-input
            v-model="form.userName"
            placeholder="请输入用户名"
          ></el-input>
        </el-form-item>
        <el-form-item label="真实姓名" prop="realName">
          <el-input
            v-model="form.realName"
            placeholder="请输入真实姓名"
          ></el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="phone" v-if="isAdd">
          <el-input v-model="form.phone" placeholder="请输入手机号"></el-input>
        </el-form-item>
        <el-form-item label="手机号" v-else>
          <el-input
            v-model="form.phone"
            disabled
            placeholder="手机号不可修改"
          ></el-input>
        </el-form-item>
        <el-form-item label="用户角色" prop="userRole">
          <el-select
            v-model="form.userRole"
            placeholder="请选择角色"
            style="width: 100%"
            :disabled="
              !isAdd &&
              form.userRole === 'superAdmin' &&
              currentUserRole !== 'superAdmin'
            "
          >
            <el-option
              label="超级管理员"
              value="superAdmin"
              :disabled="currentUserRole !== 'superAdmin'"
            ></el-option>
            <el-option label="管理员" value="admin"></el-option>
            <el-option label="老板" value="boss"></el-option>
            <el-option label="员工" value="employee"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="个人简介" prop="userProfile">
          <el-input
            v-model="form.userProfile"
            type="textarea"
            :rows="3"
            placeholder="请输入个人简介"
          ></el-input>
        </el-form-item>

        <!-- 地址信息 - 只在添加时显示 -->
        <div v-if="isAdd">
          <el-divider content-position="left">地址信息</el-divider>

          <el-form-item label="省市区" prop="selectedArea">
            <el-cascader
              v-model="form.selectedArea"
              :options="regionData"
              :props="cascaderProps"
              placeholder="请选择省市区"
              style="width: 100%"
              clearable
              @change="handleFormAreaChange"
            />
          </el-form-item>

          <el-form-item label="详细地址" prop="detailAddress">
            <el-input
              v-model="form.detailAddress"
              type="textarea"
              :rows="2"
              placeholder="请输入详细地址（街道、门牌号等）"
            ></el-input>
          </el-form-item>
        </div>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit" :loading="submitting">
            确定
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
  <div v-else class="no-permission">
    <el-result
      icon="warning"
      title="无权限访问"
      sub-title="只有管理员才能访问此页面"
    >
    </el-result>
  </div>
</template>

<script>
import { ref, reactive, computed, onMounted } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { User } from "@element-plus/icons-vue";
import * as ElementPlusIconsVue from "@element-plus/icons-vue";
import {
  getSuperAdminUserList,
  addUser,
  updateUser,
  deleteUser,
  getCurrentUser,
} from "@/api/user";
import { regionData } from "element-china-area-data";

export default {
  name: "UserList",
  setup() {
    const Plus = ElementPlusIconsVue.Plus;
    const Search = ElementPlusIconsVue.Search;
    const Edit = ElementPlusIconsVue.Edit;
    const Delete = ElementPlusIconsVue.Delete;
    const Refresh = ElementPlusIconsVue.Refresh;

    const userSearch = ref("");
    const loading = ref(false);
    const submitting = ref(false);
    const dialogVisible = ref(false);
    const isAdd = ref(true);
    const formRef = ref(null);
    const hasAdminAccess = ref(false);
    const currentUserInfo = ref(null);
    const currentUserRole = ref("");

    const currentPage = ref(1);
    const pageSize = ref(10);
    const userList = ref([]);
    const total = ref(0);

    // Cascader 配置
    const cascaderProps = {
      value: "value",
      label: "label",
      children: "children",
    };

    const form = reactive({
      id: "",
      userName: "",
      realName: "",
      phone: "",
      userRole: "",
      userProfile: "",
      selectedArea: [], // 改为数组形式存储省市区
      provinceCode: "",
      provinceName: "",
      cityCode: "",
      cityName: "",
      districtCode: "",
      districtName: "",
      detailAddress: "",
    });

    const rules = reactive({
      userName: [{ required: true, message: "请输入用户名", trigger: "blur" }],
      realName: [
        { required: true, message: "请输入真实姓名", trigger: "blur" },
      ],
      phone: [
        { required: true, message: "请输入手机号", trigger: "blur" },
        {
          pattern: /^1[3-9]\d{9}$/,
          message: "请输入正确的手机号码",
          trigger: "blur",
        },
      ],
      userRole: [
        { required: true, message: "请选择用户角色", trigger: "change" },
      ],
      userProfile: [
        { required: false, message: "请输入个人简介", trigger: "blur" },
      ],
      // 地址相关验证规则 - 修改为验证selectedArea
      selectedArea: [
        { required: true, message: "请选择省市区", trigger: "change" },
      ],
      detailAddress: [
        { required: true, message: "请输入详细地址", trigger: "blur" },
      ],
    });

    // 表单中地区选择变化
    const handleFormAreaChange = (value) => {
      if (value && value.length === 3) {
        const [provinceCode, cityCode, districtCode] = value;

        form.provinceCode = provinceCode;
        form.cityCode = cityCode;
        form.districtCode = districtCode;

        form.provinceName = getAreaNameByCode(provinceCode);

        const province = regionData.find((item) => item.value === provinceCode);
        if (province && province.children) {
          const city = province.children.find(
            (item) => item.value === cityCode
          );
          if (city) {
            form.cityName = city.label;

            if (city.children) {
              const district = city.children.find(
                (item) => item.value === districtCode
              );
              if (district) {
                form.districtName = district.label;
              }
            }
          }
        }
      } else {
        form.provinceCode = "";
        form.provinceName = "";
        form.cityCode = "";
        form.cityName = "";
        form.districtCode = "";
        form.districtName = "";
      }
    };

    // 根据地区代码获取地区名称
    const getAreaNameByCode = (code, data = regionData) => {
      for (const item of data) {
        if (item.value === code) {
          return item.label;
        }
        if (item.children) {
          const result = getAreaNameByCode(code, item.children);
          if (result) return result;
        }
      }
      return "";
    };

    // 前端搜索过滤
    const filterUsers = (users, searchKeyword) => {
      if (!searchKeyword) return users;

      const keyword = searchKeyword.toLowerCase().trim();
      return users.filter(
        (user) =>
          (user.userName && user.userName.toLowerCase().includes(keyword)) ||
          (user.realName && user.realName.toLowerCase().includes(keyword)) ||
          (user.phone && user.phone.includes(keyword)) ||
          (user.id && user.id.toString().includes(keyword))
      );
    };

    // 获取用户数据
    const fetchUsers = async () => {
      loading.value = true;
      try {
        console.log("[UserList] 开始获取用户数据");

        const response = await getSuperAdminUserList({
          pageNum: currentPage.value,
          pageSize: pageSize.value,
        });

        console.log("[UserList] 获取用户数据响应:", response);

        if (response.code === 0 && response.data) {
          const data = response.data;

          let allUsers = data.records || [];

          // 处理用户数据映射
          allUsers = allUsers.map((user) => ({
            id: user.id,
            userName: user.userName || "未设置",
            realName: user.realName || "未设置",
            phone: user.phone || "未设置",
            userRole: user.userRole || "employee",
            userProfile: user.userProfile || "暂无简介",
            createdTime: user.createdTime || user.createTime || "未知时间",
            addressId: user.addressId,
            detailAddress: user.detailAddress || "未设置地址",
          }));

          // 应用搜索过滤
          const filteredUsers = filterUsers(allUsers, userSearch.value);

          userList.value = filteredUsers;
          total.value = Number(data.totalRow) || filteredUsers.length;

          console.log("[UserList] 处理后的用户列表:", userList.value);
          console.log("[UserList] 总记录数:", total.value);

          if (userSearch.value && filteredUsers.length === 0) {
            ElMessage.warning(`未找到匹配 "${userSearch.value}" 的用户`);
          } else {
            ElMessage.success(`成功获取 ${filteredUsers.length} 个用户`);
          }
        } else {
          ElMessage.error(response.message || "获取用户列表失败");
        }
      } catch (error) {
        console.error("获取用户列表失败:", error);
        ElMessage.error("获取用户列表失败，请重试");
      } finally {
        loading.value = false;
      }
    };

    // 检查是否为管理员
    const checkAdminAccess = async () => {
      try {
        const response = await getCurrentUser();
        if (response.code === 0 && response.data) {
          currentUserInfo.value = response.data;
          const role = response.data.userRole;
          console.log("[UserList] 当前用户角色:", role);

          // 管理员和超级管理员都可以访问
          hasAdminAccess.value =
            role === "superAdmin" || role === "admin" || role === "boss";
          currentUserRole.value = role;

          if (hasAdminAccess.value) {
            fetchUsers();
          } else {
            console.warn(
              "[UserList] 没有权限访问用户列表，当前角色：",
              role || "未知"
            );
          }
        }
      } catch (error) {
        console.error("检查用户权限失败:", error);
        ElMessage.error("获取用户信息失败");
      }
    };

    // 搜索输入处理
    const handleSearchInput = () => {
      clearTimeout(window.searchTimer);
      window.searchTimer = setTimeout(() => {
        handleSearch();
      }, 500);
    };

    // 搜索
    const handleSearch = () => {
      currentPage.value = 1;
      console.log("[UserList] 执行搜索，关键词:", userSearch.value);
      fetchUsers();
    };

    // 刷新
    const handleRefresh = () => {
      userSearch.value = "";
      currentPage.value = 1;
      console.log("[UserList] 刷新数据");
      fetchUsers();
    };

    const dialogTitle = computed(() => {
      return isAdd.value ? "添加用户" : "编辑用户";
    });

    const handleAddUser = () => {
      isAdd.value = true;
      resetForm();
      dialogVisible.value = true;
    };

    const handleEdit = (row) => {
      isAdd.value = false;
      Object.assign(form, {
        id: row.id,
        userName: row.userName || "",
        realName: row.realName || "",
        phone: row.phone || "",
        userRole: row.userRole || "",
        userProfile: row.userProfile || "",
        selectedArea: [], // 重置选择区域
        provinceCode: "",
        provinceName: "",
        cityCode: "",
        cityName: "",
        districtCode: "",
        districtName: "",
        detailAddress: "",
      });
      console.log("[UserList] 编辑用户:", row);
      dialogVisible.value = true;
    };

    const handleDelete = (row) => {
      console.log("[UserList] 删除用户:", row);
      ElMessageBox.confirm(
        `确定要删除用户 "${row.realName || row.userName}" 吗？`,
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      )
        .then(async () => {
          try {
            const response = await deleteUser(row.id);
            if (response.code === 0) {
              ElMessage.success("删除成功");
              fetchUsers();
            } else {
              ElMessage.error(response.message || "删除失败");
            }
          } catch (error) {
            console.error("删除用户失败:", error);
            ElMessage.error("删除失败，请重试");
          }
        })
        .catch(() => {});
    };

    const handleSubmit = () => {
      if (!formRef.value) return;

      formRef.value.validate(async (valid) => {
        if (valid) {
          submitting.value = true;
          try {
            console.log(
              "[UserList] 提交表单数据:",
              JSON.stringify(form, null, 2)
            );

            // 准备提交数据
            const submitData = {
              id: form.id,
              userName: form.userName,
              realName: form.realName,
              phone: form.phone,
              userProfile: form.userProfile,
              userRole: form.userRole,
              provinceCode: form.provinceCode,
              provinceName: form.provinceName,
              cityCode: form.cityCode,
              cityName: form.cityName,
              districtCode: form.districtCode,
              districtName: form.districtName,
              detailAddress: form.detailAddress,
            };

            let response;
            if (isAdd.value) {
              response = await addUser(submitData);
            } else {
              // 编辑时检查权限 - 只有超级管理员可以授予超级管理员角色
              if (
                form.userRole === "superAdmin" &&
                currentUserRole.value !== "superAdmin"
              ) {
                ElMessage.error("无权授予超级管理员角色");
                return;
              }

              response = await updateUser({
                ...submitData,
                updateTime: new Date().toISOString(),
              });
            }

            console.log("[UserList] 表单提交响应:", response);

            if (response.code === 0) {
              ElMessage.success(isAdd.value ? "添加成功" : "更新成功");
              dialogVisible.value = false;
              resetForm();
              fetchUsers();
            } else {
              ElMessage.error(response.message || "操作失败");
            }
          } catch (error) {
            console.error("操作失败:", error);
            ElMessage.error(error.message || "操作失败，请重试");
          } finally {
            submitting.value = false;
          }
        }
      });
    };

    const resetForm = () => {
      if (formRef.value) {
        formRef.value.resetFields();
      }
      Object.assign(form, {
        id: "",
        userName: "",
        realName: "",
        phone: "",
        userRole: "",
        userProfile: "",
        selectedArea: [],
        provinceCode: "",
        provinceName: "",
        cityCode: "",
        cityName: "",
        districtCode: "",
        districtName: "",
        detailAddress: "",
      });
    };

    const handleSizeChange = (val) => {
      pageSize.value = val;
      currentPage.value = 1;
      console.log("[UserList] 分页大小改变:", val);
      fetchUsers();
    };

    const handleCurrentChange = (val) => {
      currentPage.value = val;
      console.log("[UserList] 当前页改变:", val);
      fetchUsers();
    };

    onMounted(() => {
      checkAdminAccess();
    });

    return {
      Plus,
      Search,
      Edit,
      Delete,
      Refresh,
      User,
      userSearch,
      loading,
      submitting,
      dialogVisible,
      isAdd,
      formRef,
      form,
      rules,
      userList,
      dialogTitle,
      currentPage,
      pageSize,
      total,
      hasAdminAccess,
      currentUserRole,
      regionData,
      cascaderProps,
      handleAddUser,
      handleEdit,
      handleDelete,
      handleSubmit,
      handleSizeChange,
      handleCurrentChange,
      handleSearch,
      handleRefresh,
      handleSearchInput,
      handleFormAreaChange,
    };
  },
};
</script>

<style scoped>
.page-title {
  font-size: 20px;
  margin-bottom: 20px;
  color: #1b9a7c;
  padding-bottom: 10px;
  border-bottom: 1px solid #e0e0e0;
  display: flex;
  align-items: center;
  gap: 8px;
}

.page-title .el-icon {
  font-size: 24px;
}

.table-operations {
  margin-bottom: 20px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.data-info {
  margin-bottom: 15px;
}

.pagination {
  margin-top: 20px;
  text-align: right;
}

.card {
  background: white;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  padding: 20px;
  margin-bottom: 20px;
}

:deep(.el-table .el-table__cell) {
  padding: 12px 0;
}

:deep(.el-tag) {
  display: inline-flex;
  align-items: center;
  gap: 4px;
}

.no-permission {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 400px;
}

:deep(.el-divider__text) {
  background-color: #f5f7fa;
  color: #606266;
  font-size: 14px;
  font-weight: 500;
}
</style>
